package com.example.cinemasystemv2.service;

import com.example.cinemasystemv2.entity.User;
import com.example.cinemasystemv2.repository.UserRepository;
import com.example.cinemasystemv2.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private SystemLogService systemLogService;
    
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
    
    public Optional<User> getUserById(Long userId) {
        return userRepository.findById(userId);
    }
    
    public Optional<User> getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public List<User> getUsersByRole(String role) {
        return userRepository.findByRole(role);
    }
    
    public List<User> getNonAdminUsers() {
        return userRepository.findNonAdminUsers();
    }
    
    public List<User> searchUsers(String keyword) {
        return userRepository.searchUsers(keyword);
    }
    
    public User saveUser(User user) {
        if (user.getRegistrationTime() == null) {
            user.setRegistrationTime(LocalDateTime.now());
        }
        User savedUser = userRepository.save(user);
        systemLogService.log("用户创建: " + user.getUsername(), user.getUsername(), "CREATE_USER");
        return savedUser;
    }
    
    public User createUser(String username, String password, String role, String phoneNumber) {
        if (userRepository.existsByUsername(username)) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // 验证手机号格式
        if (!isValidPhoneNumber(phoneNumber)) {
            throw new IllegalArgumentException("手机号格式不正确，请输入11位数字");
        }
        
        if (userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new IllegalArgumentException("手机号码已存在");
        }
        
        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(MD5Util.encrypt(password));
        user.setRole(role);
        user.setPhoneNumber(phoneNumber);
        user.setRegistrationTime(LocalDateTime.now());
        user.setMustChangePassword(true); // 新用户必须在登录时修改密码
        
        User savedUser = saveUser(user);
        systemLogService.log("增加" + role + username, "admin", "CREATE_USER");
        return savedUser;
    }
    
    public void deleteUser(Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            // 不能删除admin账户
            if ("admin".equals(user.getUsername())) {
                throw new IllegalArgumentException("不能删除admin管理员账户");
            }
            userRepository.deleteById(userId);
            systemLogService.log("删除" + user.getRole() + user.getUsername(), "admin", "DELETE_USER");
        }
    }
    
    public User updateUser(User user) {
        // 验证手机号格式
        if (!isValidPhoneNumber(user.getPhoneNumber())) {
            throw new IllegalArgumentException("手机号格式不正确，请输入11位数字");
        }
        
        // 检查手机号码唯一性（排除当前用户）
        Optional<User> existingUserWithPhone = userRepository.findAll().stream()
                .filter(u -> u.getPhoneNumber() != null && u.getPhoneNumber().equals(user.getPhoneNumber()) && !u.getUserId().equals(user.getUserId()))
                .findFirst();
        
        if (existingUserWithPhone.isPresent()) {
            throw new IllegalArgumentException("手机号码已被其他用户使用");
        }
        
        User updatedUser = userRepository.save(user);
        systemLogService.log("用户更新: " + user.getUsername(), "admin", "UPDATE_USER");
        return updatedUser;
    }
    
    public boolean changePassword(String username, String newPassword) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setPasswordHash(MD5Util.encrypt(newPassword));
            user.setMustChangePassword(false);
            userRepository.save(user);
            systemLogService.log("密码修改: " + username, username, "CHANGE_PASSWORD");
            return true;
        }
        return false;
    }
    
    public boolean changePassword(String username, String oldPassword, String newPassword) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            if (user.getPasswordHash().equals(MD5Util.encrypt(oldPassword))) {
                user.setPasswordHash(MD5Util.encrypt(newPassword));
                user.setMustChangePassword(false);
                userRepository.save(user);
                systemLogService.log("密码修改: " + username, username, "CHANGE_PASSWORD");
                return true;
            }
        }
        return false;
    }
    
    public boolean resetPassword(Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setPasswordHash(MD5Util.encrypt("123456")); // 默认密码
            user.setMustChangePassword(true);
            userRepository.save(user);
            systemLogService.log("密码重置: " + user.getUsername(), "admin", "RESET_PASSWORD");
            return true;
        }
        return false;
    }
    
    public boolean resetPassword(String username, String newPassword) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setPasswordHash(MD5Util.encrypt(newPassword));
            user.setMustChangePassword(true);
            userRepository.save(user);
            systemLogService.log("密码重置: " + username, "admin", "RESET_PASSWORD");
            return true;
        }
        return false;
    }
    
    public User authenticateUser(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            boolean authenticated = user.getPasswordHash().equals(MD5Util.encrypt(password));
            if (authenticated) {
                systemLogService.log("用户登录: " + username, username, "LOGIN");
                return user;
            }
        }
        return null;
    }
    
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }
    
    public boolean verifyPassword(String username, String password) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            return user.getPasswordHash().equals(MD5Util.encrypt(password));
        }
        return false;
    }
    
    public boolean updatePassword(String username, String newPassword) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setPasswordHash(MD5Util.encrypt(newPassword));
            user.setMustChangePassword(false);
            userRepository.save(user);
            systemLogService.log("密码修改: " + username, username, "CHANGE_PASSWORD");
            return true;
        }
        return false;
    }
    
    public boolean setPasswordChangeRequired(String username, boolean required) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            user.setMustChangePassword(required);
            userRepository.save(user);
            return true;
        }
        return false;
    }
    
    public long countUsersByRole(String role) {
        return userRepository.countByRole(role);
    }
    
    public boolean updateUserRole(Long userId, String newRole) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isPresent()) {
            User user = userOpt.get();
            String oldRole = user.getRole();
            user.setRole(newRole);
            userRepository.save(user);
            systemLogService.log("用户角色更新: " + user.getUsername() + " 从 " + oldRole + " 变更为 " + newRole, "admin", "UPDATE_USER_ROLE");
            return true;
        }
        return false;
    }
    
    /**
     * 验证手机号格式
     * @param phoneNumber 手机号
     * @return 是否为有效的手机号格式
     */
    private boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
            return false;
        }
        
        // 去除空格
        phoneNumber = phoneNumber.trim();
        
        // 检查是否为11位数字
        if (phoneNumber.length() != 11) {
            return false;
        }
        
        // 检查是否全为数字
        if (!phoneNumber.matches("\\d{11}")) {
            return false;
        }
        
        // 检查是否以1开头
        if (!phoneNumber.startsWith("1")) {
            return false;
        }
        
        return true;
    }

}